package secret.santa.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LoginPanel extends Composite 
{
	private boolean loggingIn;
	private Secret_Santa santa;
	private static LoginPanelUiBinder uiBinder = GWT
			.create(LoginPanelUiBinder.class);

	interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> 
	{
	}

	@UiField
	Button signInButton;
	@UiField
	TextBox textBoxUsername;
	@UiField
	PasswordTextBox textBoxPassword;
	@UiField
	Label statusLabel;

	public LoginPanel(Secret_Santa s) 
	{
		initWidget(uiBinder.createAndBindUi(this));
		santa = s;
	}

	@UiHandler("signInButton")
	void onClick(ClickEvent e) 
	{
		login();
	}
	@UiHandler("textBoxUsername")
	void onKeyDownUsername(KeyDownEvent e)
	{
		if(e.getNativeKeyCode() == KeyCodes.KEY_ENTER)
		{
			login();	
		}
	}
	@UiHandler("textBoxPassword")
	void onKeyDownPassword(KeyDownEvent e)
	{
		if(e.getNativeKeyCode() == KeyCodes.KEY_ENTER)
		{
			login();	
		}
	}
	private void login()
	{
		if(loggingIn)
			return;
		signInButton.setEnabled(false);
		loggingIn = true;
		String username = textBoxUsername.getText();
		String password = textBoxPassword.getText();
		
		if(username.length() == 0 || password.length() == 0)
			Window.alert("Username or password is empty.");
		else
			santa.login(username, password);
		textBoxUsername.setText("");
		textBoxUsername.setText("");
		
	}
	public void loggedIn()
	{
		removeFromParent();
		loggingIn = false;
		signInButton.setEnabled(true);
	}
	public void notLoggedIn()
	{
		loggingIn = false;
		signInButton.setEnabled(true);
	}

	public void setStatus(String status) 
	{
		statusLabel.setText(status);		
	}
	

}
